import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common'
import { ErrorCode } from '@/shared/constants/error.constants'

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException | Error, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse()
    const request = ctx.getRequest()

    let message = exception.message
    Logger.log('错误提示', message)
    console.log('exception: ', exception)

    if (exception instanceof HttpException) {
      const error = exception.getResponse()
      message = error['message']
    }

    const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR
    const msg = ErrorCode.HasCode(status) ? ErrorCode.CodeToMessage(status) : '请求失败'
    Logger.log('status', status)

    const errorResponse = {
      data: {
        error: message,
      }, // 获取全部的错误信息
      message: msg,
      code: status, // 自定义code
      url: request.originalUrl, // 错误的url地址
      timestamp: new Date().toISOString(),
    }

    // 设置返回的状态码、发送错误信息
    response.status(status).json(errorResponse)
  }
}
